<template>
  <a-config-provider :locale="currentLanguage">
    <full-loading :show="isFullLoading" :text="loadingText" />
    <router-view />
  </a-config-provider>
</template>

<script lang="ts" setup>
import { computed, provide } from 'vue';
import { Locales, TranslateTable, useI18nApp, LanguageNameList } from '@/i18n';
import { useAppStore } from '@/pinia/modules/app';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';

// 测试lint
const appStore = useAppStore();
const { i18nInstance } = useI18nApp();
const { i18n } = i18nInstance;

function _set(lang: keyof typeof TranslateTable): keyof typeof TranslateTable {
  i18nInstance.locale.value = lang as any;
  // 设置当前语言的时间, ant-design-vue@3 之后将moment替换为dayjs
  dayjs.locale(TranslateTable[lang]);
  appStore.setLanguage(lang);
  return lang;
}

/**
 * @functin setLang - set the app's language
 * @param {string} lang - the language will be setted
 * @return {string} lang - langguage name
 */
function setLang(lang: string): Promise<keyof typeof TranslateTable | 'same'> {
  if (lang === i18nInstance.locale.value) {
    return Promise.resolve('same');
  }
  return Promise.resolve(_set(lang));
}

const isFullLoading = computed(() => appStore.fullLoading);
const loadingText = computed(() => appStore.loadingText);
const currentLanguage = computed(() => Locales[appStore.language]);

const changeLanguage = (lang: keyof typeof LanguageNameList) => {
  setLang(lang as string).then(result => {
    if (result === lang) {
      message.success(
        `${i18n.value['Current Language:']} ${i18n.value.languageName}`,
      );
    }
  });
};

// 默认设置为中文
setLang('zhCN');

// 向下提供修改语言的方法
provide('changeLanguage', changeLanguage);
</script>
